/**
 * 公共服务方法.
 */
import $ from '~plugins/jquery.vendor'
import $_fn from '~plugins'
// import UE from '~plugins/jquery.ueditor'
class rootFun {
    constructor($rootScope,$location,$timeout,$interval) {
        //this.$scope=$scope,
        this.$rootScope = $rootScope,
        this.$location = $location,
        this.$timeout  = $timeout,
        this.$interval = $interval,
        this.HasParam = null
        this.focusType =  null
        this.timem = null
        this.mess = null
        this.$rootScope.paramPath = {}
        this.$rootScope.param={}
        /*禹 记录状态*/
        this.$rootScope.revisit = {
            data: '',
            status: ''
        }
    }

    //模块之间跳转
    changeHas(has, param) {
        this.$location.path('/' + has).replace()								//转换路由
        $('#nav-parent li a').removeClass('actives')						//一级导航改变高亮
        $('#nav-parent .' + has + ' a').addClass('actives')
        this.HasParam = param
        this.$rootScope.paramPath.path = param									//传参	用于判断指定跳转二级目录
    }
    closeMess (ele, time) {
        clearTimeout(time.time)
        $('.' + ele).css('display', 'none')
        $('.' + ele).css({'right': '-250px'})
    }
    HasLoad() {
        var count = null
        if (this.HasParam) {
            $('.temList li').removeClass('light')
            if (this.HasParam == 'clientList') count = 'HbHr.hr36'							//赋值当前二级导航下所属的位置
            if (this.HasParam == 'pressureList') count = 'HbHr.hr39'
            if (this.HasParam == 'messgModel') count = 'HbHr.hr48'
            /***控制台跳转***/
            if (this.HasParam == 'PoInputList' || this.HasParam == 'PoInput' || this.HasParam == 'orderRntry')                    count = 'HbHr.hr12'
            if (this.HasParam == 'PoAssessList' || this.HasParam == 'PoAssessListBe')            count = 'HbHr.hr13'
            if (this.HasParam == 'PoFaceList' || this.HasParam == 'orderFaceListBefore')            count = 'HbHr.hr14'
            if (this.HasParam == 'rejectList')                                            count = 'HbHr.hr40'
            if (this.HasParam == 'hyjectList')                                            count = 'HbHr.hr300'
            if (this.HasParam == 'lineCheckList' || this.HasParam == 'riskControlListBefore')    count = 'HbHr.hr15'
            if (this.HasParam == 'sriskCtrlList' || this.HasParam == 'sriskCtrlListBefore')    count = 'HbHr.hr16'
            if (this.HasParam == 'storeManList')                                            count = 'HbHr.hr17'
            if (this.HasParam == 'BriskCtrlList' || this.HasParam == 'BriskCtrlListBefore')    count = 'HbHr.hr18'
            if (this.HasParam == 'areaManList' || this.HasParam == 'areaManListBefore')        count = 'HbHr.hr19'
            if (this.HasParam == 'ContractMng' || this.HasParam == 'historyList'|| this.HasParam == 'contractNumManag')                count = 'HbHr.hr20'
            if (this.HasParam == 'mortgageReg')                                            count = 'HbHr.hr21'
            if (this.HasParam == 'finalAudit' || this.HasParam == 'haveCheck')                    count = 'HbHr.hr22'
            if (this.HasParam == 'revisitManeg' || this.HasParam == 'revisitManegToday')        count = 'HbHr.hr23'
            if (this.HasParam == 'serviceCollect')                                        count = 'HbHr.hr24'
            if (this.HasParam == 'supportCollet')                                        count = 'HbHr.hr25'
            if (this.HasParam == 'tracManeg' || this.HasParam == 'attachmentList')            count = 'HbHr.hr26'
            if (this.HasParam == 'waitingLoan')                                            count = 'HbHr.hr27'
            if (this.HasParam == 'normalRepayment')                                        count = 'HbHr.hr28'
            if (this.HasParam == 'backArrivalList' || this.HasParam == 'backList')            count = 'HbHr.hr29'
            if (this.HasParam == 'partialRepayment')                                        count = 'HbHr.hr30'
            if (this.HasParam == 'breachContract')                                        count = 'HbHr.hr31'
            if (this.HasParam == 'settled')                                                count = 'HbHr.hr32'
            if (this.HasParam == 'depositNo')                                            count = 'HbHr.hr33'
            if (this.HasParam == 'collectionDetails' || this.HasParam == 'fangDetails')                                    count = 'HbHr.hr34'
            if (this.HasParam == 'badDebtList')                                            count = 'HbHr.hr35'
            if (this.HasParam == 'clientCount')                                            count = 'HbHr.hr36'
            if (this.HasParam == 'financeCount')                                            count = 'HbHr.hr37'
            if (this.HasParam == 'othersCount')                                            count = 'HbHr.hr38'
            setTimeout(function () {
                $('.temList li').each(function () {
                    var HbHr = $(this).attr('ng-if')
                    if (count == HbHr) {
                        $(this).addClass('light')
                    }
                })
            })
            this.HasParam = null
        } else {																//否则就默认第一个添加高亮
            setTimeout(function () {
                $('.temList li').eq(0).addClass('light')
            })
        }
    }
    //按钮带参数 页面跳转 弹出窗
    btnQuery(_this,selectName) {
        var path=$('.'+_this).attr('path')						//二级模板路径参数
        var params=$('.'+_this).attr('params')					//三级模板路径参数
        var param=$('.'+_this).attr('param')					//传参
        var type=$('.'+_this).attr('data-type')				//type = 1 跳转
        var $event=$('.'+_this)								//无意义
        if (!$_fn.isNull(param)) {
            this.$rootScope.default = $_fn._paramValues(param)			//赋值获取对象进行传参
        }
        if (!$_fn.isNull(selectName)) {
            this.$rootScope.defaultSelect = $_fn._fromCheckValue(selectName) //多选框的值
            if($_fn.isNull(this.$rootScope.defaultSelect))
            {
                $_fn.Message('F','请选择操作项')
                return 
            }

        }
        if($_fn.isNull(path))
        {
            $_fn.Message('F','参数错误,弹出框为空')
            return
        }
        if(type == 1) {
            this.toggleView(path,params)
        }
        else{
            this.boxTem(path,params,$event)
        }
    }
    btn (i) {
		this.$rootScope.param.pageNum=i
		console.log(this.$rootScope.param)
		if(this.$rootScope.param.timeType && (!this.$rootScope.param.start_time && !this.$rootScope.param.end_time)){
				$_fn.Message('F','请选择时间')
				return
		}
		if(this.$rootScope.param.end_time&&!this.$rootScope.param.timeType){
			$_fn.Message('F','请选择时间类型')
				return
		}
		if(this.$rootScope.param.start_time&&!this.$rootScope.param.timeType){
			$_fn.Message('F','请选择时间类型')
				return
		}
		if(this.$rootScope.param.type && !this.$rootScope.param.name){
				$_fn.Message('F','请输入关键字')
				return
		}
		if(this.$rootScope.param.name&&!this.$rootScope.param.type){
				$_fn.Message('F','请选择字段')
				return
		}
		console.log('开始搜索')
		this.$rootScope.sel(i)
	}
    //点击切换index二级栏目
    toggleView(path, params, focus, status) {
        let _this = this
        var routeNull = 'components/common/defaultBox.html'		//清空地址 实现二级导航点击刷新
        var route = ''
        setTimeout(function () {
            path == 'common' && (path = _this.$location.$$path.split('/')[1])
            route = 'components/' + path + '/include/' + params + '.html'
            _this.$rootScope.$apply(function(){
                _this.$rootScope[path] = routeNull
            })
            _this.$rootScope.$apply(function(){
                _this.$rootScope[path] = route
            })
        })
        if (focus){
            var _target = $(focus.target)
            var isCalss =  _target.hasClass('public-List')
            var param = _target.attr('params')
            _this.$rootScope.LinkParams = param
            if (!isCalss) {
                //如果focus为undefined就不执行 二级导航点击高亮
                _target.siblings('li').removeClass()
                _target.addClass('light')
                _this.$rootScope.focusIndex = 0  //全局设置菜单高亮索引
                _this.$rootScope.payPlan = _target.attr('param')
            }
            //用于内部子菜单点击高亮
            if (isCalss) {
                _this.$rootScope.focusIndex = parseInt(_target.index())-1
            }
        }

        /*禹  记录页面跳转是否使用上一个状态的数据*/
        !_this.$rootScope.revisit[params] &&(_this.$rootScope.revisit[params] = {})
        if (status) {
            //初始化搜索信息，status = 'N'时，把当前页面的初始值保存在data中。
            if (!_this.$rootScope.revisit[params].status) {
                _this.$rootScope.revisit[params].status = 'N'
            } else {
                _this.$rootScope.revisit[params].status = status
            }

        } else {
            _this.$rootScope.revisit[params].status = 'N'
        }
        // console.log('status:', _this.$rootScope.revisit,_this.$rootScope.revisit[params])
    }
    //导航栏右边个人信息对应的侧边栏转换
    navRightBtn (index) {
        var secondParam
        switch (index) {
            case 0:
                secondParam = 'personIn'
                break
            case 1:
                secondParam = 'myLims'
                break
            case 2:
                secondParam = 'zhanMessg'
                break
            case 3:
                secondParam = 'changePsw'
                break
            default:
                break
        }
        this.$rootScope.paramPath.path = secondParam;
        this.toggleView('informa', secondParam)
        this.$timeout(function () {
            $('.temList li').eq(index).addClass('light').siblings('li').removeClass()
        }, 200)
    }
    ajaxfenQi(){
        var _this = this
        var param={}
        $_fn.ajaxPost('manager/selectApplyTermList.do',param,function(data){
            _this.$rootScope.fenQi = data.content
        })
    }
    addUserHelp(){
        if(localStorage.getItem('userHelp')){
            var userHelp=JSON.parse(localStorage.getItem('userHelp') )
            this.$rootScope.userHelp = userHelp
            $('.admin').text(this.$rootScope.userHelp.admin.realName)
            $('#admin-level').text(this.$rootScope.userHelp.admin.departmentName)
        }else{
            // $.ajaxPost('manager/loginOut.do','',function(data){
            // 	if(data.type>0){
            // 		$rootScope.$apply(function(){
            // 			$location.path('/logIn')
            // 			$interval.cancel(mess)
            // 		})
            // 		localStorage.removeItem('userHelp')
            // 	}
            // })
        }
    }
    logInsuc (){
        var _this = this
        var zhanMessgR = function(){
            var _message = $('.zhanneixin-message')
            $_fn.ajaxPost_('manager/selectUnreadNum.do','',function (data) {
                if(data.content==0){
                    _message.css('display','none')
                }else{
                    _message.css('display','block')
                }
                _this.$timeout(function(){
                    $_fn.ajaxPost_('manager/consoleMessage.do',{},function (data) {
                        _this.$rootScope.$apply(function(){
                            if(data.type>0){
                                if(data.content.length>0){
                                    $('.no-show').hide()
                                    $('.all-messg').show()
                                    _this.$rootScope.newMessg=data
                                }
                            }
                        })
                    })
                },3100)
            })
        }
        _this.timem = _this.$timeout(function(){
            zhanMessgR()
        },10)
        _this.mess = _this.$interval(function(){
            zhanMessgR()
        },300000)
    }
    //部门
    ajaxbuMen (){
         var param={}
        var _this =this
         $_fn.ajaxPost('manager/selectDepartmentList.do',param,function(data){//console.log(data)
             _this.$rootScope.buMen = data
        })
    }
    //页面加载完成后调用
    load () {
        this.focusLocat()										//禹		用来解决增加ng-if后代码异步问题 增加3级导航高亮
        $_fn.clickBind()
        $_fn.loadHead()
    }
    focusLocat (){
        var _this = this
        if(_this.focusType == 1) { 													//通过selectQuery中的type重新赋值判断 如果为1执行
            _this.$timeout(function(){
                if(!_this.$rootScope.default.locat) {
                    _this.$rootScope.default.locat = 0
                }
                focus(_this.$rootScope.default.locat)
                _this.focusType = null							//重新清空
                $_fn.loadHead()							//磊哥 实现您的位置
            },100)
        }
    }
    tabClick(event){
        var _tr = $(event.target).parents('tr')
        if(_tr.hasClass('table-focus')){
            _tr.removeClass('table-focus')
            // _tr.find('input').removeAttr('checked')
            _tr.find('input').prop('checked', '')
        }
        else{
            _tr.addClass('table-focus')
            _tr.find('input').prop('checked',true)
        }
    }
    selectQuery (_this,selectName) {
        this.$rootScope.selectType.default = '-1'
        this.$rootScope.LinkParams = 2
        var _option = $('.'+_this).find('option:selected')
        var path = _option.attr('path')		                 //二级模板路径参数
        var params = _option.attr('params')               	 //三级模板路径参数
        var param =_option.attr('param')                     //传参
        var dataItem =_option.attr('data-item')	  
        console.log('dataItem:', dataItem)               //传参
        var type = parseInt(_option.attr('data-type'))                 //type = 1 跳转
        var $event=$('.'+_this)								 //无意义
        if (!$_fn.isNull(param)) {
            this.$rootScope.default = $_fn._paramValues(param)                  //赋值获取对象进行传参
        }
        if (!$_fn.isNull(selectName)) {
            this.$rootScope.defaultSelect = $_fn._fromCheckValue(selectName) 	//多选框的值
            if($_fn.isNull(this.$rootScope.defaultSelect))
            {
                $_fn.Message('F','请选择操作项')
                return
            }

        }
        if($_fn.isNull(path))
        {
            $_fn.Message('F','参数错误,弹出框为空')
            return
        }
        if(type == 1) {
            this.toggleView(path,params)
            this.focusType = 1
        }
        else if(type == 3){
            $_fn.Message('I','不可操作，该合同关联订单已放款！')
        }
        else{
            this.boxTem(path,params,$event)
        }
        if(dataItem){
            this.$rootScope.dataItem = dataItem
        }
    }
    UEditorContent (calss,content) {
        window.UE.getEditor1(calss).execCommand('insertHtml', content)
    }
	getTextarea (ele,content){
		$('#'+ele).insertContent( content );
	}
    boxTem (path,params,$event){
        //把模板显示出来
        var pageNum = $($event.target).attr('param')
        //console.log(pageNum)
        if('fromView'==$($event.target).attr('data-type')){
            this.$rootScope.default = $_fn._paramValues(pageNum)				//传值 在directive可以获取到
        }else{
            this.$rootScope.btnBox = $_fn._paramValues(pageNum)				//传值 在directive可以获取到
        }
        //加载对应的自定义指令模板        
        var route = 'jsp/'+ path +'/include/'+ params +'.html'
        //赋值 $rootScope.box在index.html 78行
        this.$rootScope.box = route
        console.log(route)
        //把模板显示出来
        this.showWin()
    }
    showWin (bool){
        var box = $('.winBox')
        if(bool=='hide'){
            box.css('display','none')
            this.$rootScope.componentShow.people = false								//提醒选择人员是否有下一审核人员
            this.$rootScope.box = 'components/common/defaultBox.html'						//弹窗清空
            this.$rootScope.defaultSelect = {}
            this.$rootScope.default = {}
        }else{
            console.log(box.attr('class'))
            box.css('display','block')
        }
    }
    getObject (key) {
		return JSON.parse(window.localStorage[key] || '{}');
	}
    //全选
    ch_id_all (e,name){
        var _checked = $(':checkbox[name=' + name + ']')
        if($(e.target).prop('checked')){
            _checked.each(function(){
                if(!$(this).attr('disabled')) {
                    $(this).prop('checked', true)
                }
            })
        }else{
            _checked.each(function(){
                // $(this).removeAttr('checked')
                if(!$(this).attr('disabled')){
                   $(this).prop('checked','')
                }
            })
        }
    }
    stopPropagation ($event){
        $event.stopPropagation()
    }
    remHight(){													//去除报错高亮
        for(var i in this.$rootScope.redErr){
            this.$rootScope.redErr[i] = false
        }
    }
    imgList (id){
        setTimeout(function(){
            $('#gallery'+id).rebox({ selector: 'a' })
        },200)
    }
    loadImage (url,target) {
        var img = new Image();
            img.src = url;
            // if (img.complete) {
            //     console.log('compennt-yes:',img.src)
            //     $('.'+target).removeClass('load').attr('src',img.src)
            //     return
            // }
            img.onload = function () {
                $('.'+target).removeClass('load').attr('src',img.src)
            }
    }
    onloadMsg(s){
        if(s<0) this.$rootScope.componentShow.people = true
    }
    plusBox(){													//打开图片集
        this.$rootScope.boxPlus = 'components/common/plusBox/plusBox.html'
        $('.winBox').css('display','none')
        $('.winBoxPlus').css('display','block')
    }
    hidePlusBox(p){												//关闭图片集
        if(p == 'hide'){
            $('.winBox').css('display','block')
            $('.winBoxPlus').css('display','none')
            this.$rootScope.boxPlus = 'components/common/defaultBox.html'						//弹窗图片集清空
        }
    }
    deleImgs (e){													//图片集删除方法
        this.stopBOM(e)
        this.$rootScope.Imgs.splice(e.target.getAttribute('data-idx'),1)
    }
    showImgs(){													//显示查看图片按钮
        if(this.$rootScope.Imgs.length>0){
            $('#icondian').css('display','inline-block')
        } else {
            $('#icondian').css('display', 'none')
        }
    }
    Attach () {
        let _this = this
        $_fn.ajaxPost('manager/selectAttachmentTypeList.do',{},function(data){
            if(data.type > 0){
                //写入查看订单页面公共对象
                _this.$rootScope.AttachSele = data.content
            }
        })
    }
    loadScript (path,callback){
		var oHead = document.getElementsByTagName('head')[0];
		if(oHead)
		{
			var oScript = document.createElement('script');
			oScript.setAttribute('src',path);
			oScript.setAttribute('type','text/javascript');
			oScript.setAttribute('charset','utf-8');
			oScript.onreadystatechange = function()
			{
				if (this.readyState == 'complete' || this.readyState == 'loaded')
				{
					callback();
				}
			};
			oScript.onload = callback;
			oHead.appendChild(oScript);
		}
	}
    /*
     * 设置、获取教育程度
     */
    educationLevel(level, getLevNum) {
        console.log('educationLevel',level)
        let eduData = [
            {id:'1', name:'博士'},
            {id:'2', name:'硕士'},
            {id:'3', name:'本科'},
            {id:'3', name:'大专'},
            {id:'4', name:'中专'},
            {id:'5', name:'高中'},
            {id:'6', name:'初中'},
            {id:'7', name:'小学'},
            {id:'8', name:'无'}
        ]
        if(getLevNum) {
            let eduNum = ''
            for (let i=0; i<eduData.length; i++) {
                if (eduData[i].id == level || eduData[i].name == level) {
                    eduNum = eduData[i].id
                    return eduNum
                }
            }
            return eduNum
        }
        if (level) {
            let eduName = ''
            for (let i=0; i<eduData.length; i++) {
                if (eduData[i].id == level) {
                    eduName = eduData[i].name
                    return eduName
                }
            }
            return level
        }
        return eduData
    }

}
rootFun.$injecter = ['$rootScope','$location','$timeout','$interval']
export default angular.module('rootfun', [])
    .service('rootfun', rootFun)
    .name
